package com.tgky.ybzb.utils;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson.JSONObject;

import java.io.*;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

@Slf4j
public class CommonUtil {

    /**
     * 根据文件名后缀 启动文件到指定位置
     *
     * @param sourceFolderPath
     * @param targetFolderPath
     * @param SuffixString
     */
    public static void moveFilesWithSuffix(String sourceFolderPath, String targetFolderPath, String SuffixString) {

        File sourceFolder = new File(sourceFolderPath);
        File[] files = sourceFolder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(SuffixString)) {
                    try {
                        Path sourcrPath = Paths.get(file.getAbsolutePath());
                        Path targetPath = Paths.get(targetFolderPath, file.getName());
                        Files.move(sourcrPath, targetPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }


    /**
     * 获得最大最小值
     *
     * @param arr
     */
    public static JSONObject findMaxMin(List<Double> arr) {

        JSONObject maxMin = new JSONObject();

        Double max = arr.get(0);
        Double min = arr.get(0);

        for (Double a : arr) {

            if (a > max) {
                max = a;
            }

            if (a < min) {
                min = a;
            }

        }

//        maxMin.put("max", max);
        maxMin.put("max", Math.random());
//        maxMin.put("min", min);

        return maxMin;


    }


    public static List<Long> toList(String ids) {
        if (ids != null && !ids.isEmpty()) {
            String[] strArr = ids.split(",");
            Long[] longArr = new Long[strArr.length];

            for (int i = 0; i < strArr.length; ++i) {
                Long v = Long.valueOf(strArr[i]);
                longArr[i] = v;
            }

            return Arrays.asList(longArr);
        } else {
            return new ArrayList();
        }
    }

    public static <T> String toStr(List<T> list) {
        if (list != null && !list.isEmpty()) {
            Iterator<T> it = list.iterator();
            StringJoiner sj = new StringJoiner(",");

            while (it.hasNext()) {
                sj.add(String.valueOf(it.next()));
            }

            return sj.toString();
        } else {
            return "";
        }
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }

        return dest;
    }

    public static String camelName(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && !name.isEmpty()) {
            if (!name.contains("_")) {
                return name.substring(0, 1).toLowerCase() + name.substring(1).toLowerCase();
            } else {
                String[] camels = name.split("_");
                String[] var3 = camels;
                int var4 = camels.length;

                for (int var5 = 0; var5 < var4; ++var5) {
                    String camel = var3[var5];
                    if (!camel.isEmpty()) {
                        if (result.length() == 0) {
                            result.append(camel.toLowerCase());
                        } else {
                            result.append(camel.substring(0, 1).toUpperCase());
                            result.append(camel.substring(1).toLowerCase());
                        }
                    }
                }

                return result.toString();
            }
        } else {
            return "";
        }
    }

    public static String camelNames(String names) {
        if (names != null && !names.equals("")) {
            StringBuffer sf = new StringBuffer();
            String[] fs = names.split(",");
            String[] var3 = fs;
            int var4 = fs.length;

            for (int var5 = 0; var5 < var4; ++var5) {
                String field = var3[var5];
                field = camelName(field);
                sf.append(field + ",");
            }

            String result = sf.toString();
            return result.substring(0, result.length() - 1);
        } else {
            return null;
        }
    }

    public static String camelNameCapFirst(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && !name.isEmpty()) {
            if (!name.contains("_")) {
                return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
            } else {
                String[] camels = name.split("_");
                String[] var3 = camels;
                int var4 = camels.length;

                for (int var5 = 0; var5 < var4; ++var5) {
                    String camel = var3[var5];
                    if (!camel.isEmpty()) {
                        result.append(camel.substring(0, 1).toUpperCase());
                        result.append(camel.substring(1).toLowerCase());
                    }
                }

                return result.toString();
            }
        } else {
            return "";
        }
    }

    public static String camelToUnderline(String para) {
        if (para.length() < 3) {
            return para.toLowerCase();
        } else {
            StringBuilder sb = new StringBuilder(para);
            int temp = 0;

            for (int i = 2; i < para.length(); ++i) {
                if (Character.isUpperCase(para.charAt(i))) {
                    sb.insert(i + temp, "_");
                    ++temp;
                }
            }

            return sb.toString().toLowerCase();
        }
    }


    public static void copyFileToFolder(String sourceFilePath, String targetFilePath) {


        Path sourcePath = Paths.get(sourceFilePath);
        Path targetPath = Paths.get(targetFilePath);


        try {
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            log.info("File Copy {} -> {} SUCCESS", sourceFilePath, targetFilePath);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            log.info("File Copy {} -> {} ERROR", sourceFilePath, targetFilePath);
        }


    }


    // 16进制  转  10进制
    public static int getHexToDEC(String hexString) {

        if (hexString.startsWith("0x") || hexString.startsWith("0X")) {
            hexString = hexString.substring(2);
            hexString.toUpperCase();
            return Integer.parseInt(hexString, 16);
        }
        return Integer.parseInt(hexString);

    }

    /**
     * 上传模型方法
     * @return
     */
    public static String uploadMxFile(MultipartFile file,String path){
        String fileName=file.getOriginalFilename();
        File filePath=new File(path);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        try{
            // 执行文件上传方法
            file.transferTo(new File(path+fileName));
        }catch (Exception e){
            e.printStackTrace();
        }
        return path+fileName;
    }

    /**
     * 解压模型压缩包
     * @param zipFilePath 压缩包路径
     * @param destDirectory 解压的路径
     */
    public static void unzipUsingCommonsCompress(String zipFilePath,String destDirectory){
        File sourceFile = new File(zipFilePath);
        File destinationDir = new File(destDirectory);
        if (!destinationDir.exists()) {
            destinationDir.mkdirs();
        }

        try (FileInputStream fis = new FileInputStream(sourceFile);
             BufferedInputStream bis = new BufferedInputStream(fis);
             ArchiveInputStream in = getArchiveInputStream(bis)) {

            ArchiveEntry entry;
            while ((entry = in.getNextEntry())!= null) {
                if (entry.isDirectory()) {
                    File dir = new File(destinationDir, entry.getName());
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                } else {
                    File outputFile = new File(destinationDir, entry.getName());
                    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                        IOUtils.copy(in, fos);
                    }
                }
            }
            System.out.println("解压成功！");
            log.info("+++++++++++++++解压成功++++++++++++++",zipFilePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private static ArchiveInputStream getArchiveInputStream(BufferedInputStream bis) throws IOException {
        // 判断压缩包类型并返回相应的输入流
        if (isZip(bis)) {
            return new ZipArchiveInputStream(bis);
        } else if (isTar(bis)) {
            return new TarArchiveInputStream(bis);
        } else {
            throw new IllegalArgumentException("Unsupported archive format.");
        }
    }
    private static boolean isZip(BufferedInputStream bis) throws IOException {
        byte[] signature = new byte[4];
        bis.mark(4);
        bis.read(signature);
        bis.reset();
        return signature[0] == 'P' && signature[1] == 'K' && signature[2] == 3 && signature[3] == 4;
    }

    private static boolean isTar(BufferedInputStream bis) throws IOException {
        byte[] signature = new byte[257];
        bis.mark(257);
        bis.read(signature);
        bis.reset();
        return signature[256] == 'u' && signature[255] == 's' && signature[254] == 't' && signature[253] == 'a' && signature[252] == 'r';
    }
}
